<template>
  <el-card class="box-card el-card-flex">
    <div slot="header" class="clearfix">
      <span>
        <i class="el-icon-user"></i>
        用户管理
      </span>
    </div>
    <!-- 表单 -->
    <div class="text item">
      <el-form :inline="true" class="demo-form-inline" style="float: left;height:43px" @submit.native.prevent>
        <!-- 左侧搜索按钮 -->
        <el-form-item>
          <el-input clearable v-model="textSearch" placeholder="请输入用户名/别名" style="width:240px;" @keyup.enter.native="getUserListTwo"
            @clear="getUserListOne">
            <el-button slot="append" icon="el-icon-search" @click="getUserListTwo"></el-button>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="advancedQuery">
            高级查询
            <i class="el-icon-magic-stick"></i>
          </el-button>
        </el-form-item>
        <!-- 右侧操作按钮 -->
        <el-form-item style="float:right">
          <el-button @click="handleadd" type="primary" plain>
            新增
            <i class="el-icon-plus"></i>
          </el-button>
        </el-form-item>
      </el-form>
      <!-- 表格 -->
      <div class="el-flex el-box-column">
        <el-table :data="tableData" ref="tableData" height="100%" style="width: 100%" border stripe>
          <el-table-column show-overflow-tooltip sortable min-width="100" align="center" prop="userName" label="用户名"></el-table-column>
          <el-table-column show-overflow-tooltip sortable min-width="90" align="center" prop="name" label="别名"></el-table-column>
          <el-table-column show-overflow-tooltip sortable min-width="100" align="center" prop="userTypeName" label="用户类型"></el-table-column>
          <el-table-column show-overflow-tooltip sortable min-width="100" prop="email" align="center" label="邮箱"></el-table-column>
          <el-table-column show-overflow-tooltip sortable min-width="100" prop="createName" align="center" label="创建人"></el-table-column>
          <el-table-column show-overflow-tooltip sortable min-width="147" prop="createdTime" align="center" label="创建时间"></el-table-column>
          <el-table-column min-width="280" sortable prop="roleNameArr" label="所属角色" align="left">
            <template slot-scope="scope">
              <el-popover trigger="hover" placement="top">
                <p>{{ scope.row.roleNameArr?scope.row.roleNameArr.join('/'):''}}</p>
                <div slot="reference" class="table-title-word">
                  <el-tag style="cursor: pointer;margin-right: 5px;" v-for='(item,index) in scope.row.roleNameArr' :key='index'
                    size="mini">{{item}}</el-tag>
                </div>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column min-width="280" sortable prop="userGroupNameArr" label="所属用户组" align="left">
            <template slot-scope="scope">
              <el-popover trigger="hover" placement="top">
                <p>{{ scope.row.userGroupNameArr?scope.row.userGroupNameArr.join('/'):''}}</p>
                <div slot="reference" class="table-title-word">
                  <el-tag style="cursor: pointer;margin-right: 5px;" v-for='(item,index) in scope.row.userGroupNameArr'
                    :key='index' size="mini">{{item}}</el-tag>
                </div>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column sortable prop="status" width="110" align="center" label="状态" fixed="right">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.status" active-value="1" inactive-value="0" @change="modifyState(scope.$index, scope.row)"></el-switch>
            </template>
          </el-table-column>
          <el-table-column prop="control" align="center" label="操作" width="190" fixed="right">
            <template slot-scope="scope">
              <el-button class="td-btn-icon" type="text" icon="el-icon-edit" title="编辑" @click="handleEdit(scope.$index, scope.row)"></el-button>
              <el-button class="td-btn-icon" type="text" title="密码重置" @click="reset(scope.$index, scope.row)"><i class="el-icon-unlock"></i>
              </el-button>
              <el-button class="td-btn-icon" type="text" icon="el-icon-user" title="分配角色" @click="handleRoleNames(scope.$index, scope.row)"></el-button>
              <el-button class="td-btn-icon" type="text" icon="el-icon-pie-chart" title="分配用户组" @click="handleUserGroupNames(scope.$index, scope.row)"></el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页表格 -->
        <el-pagination background layout="total, sizes, prev, pager, next, jumper" :current-page="currentPage"
          :page-size="pageSize" :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange"></el-pagination>
        <!-- 高级查询抽屉式弹框 -->
        <el-drawer title="高级查询" :visible.sync="dialogVisibleSearch" :before-close="searchClose" direction="rtl"
          custom-class="demo-drawer" ref="drawer" :close-on-press-escape="false">
          <div class="demo-drawer__content el-box-column" style="height: 100%; margin-right:10px;">
            <el-form label-width="90px" ref="AdvancedQuery" :model="AdvancedQuery" class="el-flex">
              <el-form-item label="用户名" prop="userName">
                <el-col :span="24">
                  <el-input v-model="AdvancedQuery.userName" placeholder="请输入用户名" auto-complete="off"></el-input>
                </el-col>
              </el-form-item>
              <el-form-item label="别名" prop="name">
                <el-col :span="24">
                  <el-input v-model="AdvancedQuery.name" placeholder="请输入别名" auto-complete="off"></el-input>
                </el-col>
              </el-form-item>
              <el-form-item label="状态" prop="status">
                <el-col :span="24">
                  <el-radio-group v-model="AdvancedQuery.status">
                    <el-radio label='' border>全部</el-radio>
                    <el-radio label="1" border>启用</el-radio>
                    <el-radio label="0" border>禁用</el-radio>
                  </el-radio-group>
                </el-col>
              </el-form-item>
              <el-form-item label="用户类型" prop="userType">
                <el-col :span="24">
                  <el-select clearable v-model="AdvancedQuery.userType" placeholder="请选择用户类型">
                    <el-option v-for="item in orgDegreeItems" :key="item.value" :label="item.name" :value="item.id">
                    </el-option>
                  </el-select>
                </el-col>
              </el-form-item>
            </el-form>
            <div class="demo-drawer__footer" style="text-align: right; margin-bottom: 10px; padding-right:10px;">
              <el-button type="primary" @click="getUserListThree">确定<i class="el-icon-document-checked el-icon--right"></i></el-button>
              <el-button @click="restDrawer">重置
                <i class="el-icon-refresh-left"></i>
              </el-button>
            </div>
          </div>
        </el-drawer>
        <!-- 新增或修改编辑弹框 -->
        <el-dialog :title="modalTitle" :visible.sync="dialogVisible" :close-on-click-modal="false"
          :close-on-press-escape="false" :before-close="handleAddClose" class="elAdded">
          <div class="container">
            <el-form label-width="140px" ref="editData" :model="editData" :rules="ruleValidate">
              <el-form-item label="用户名" prop="userName">
                <el-col :span="18">
                  <el-input v-model="editData.userName" :readonly="roleCodeReadonly" placeholder="请输入用户名" auto-complete="off"></el-input>
                </el-col>
              </el-form-item>
              <el-form-item label="别名" prop="name">
                <el-col :span="18">
                  <el-input v-model="editData.name" placeholder="请输入别名" auto-complete="off"></el-input>
                </el-col>
              </el-form-item>
              <el-form-item label="用户类型" prop="userType">
                <el-col>
                  <el-radio-group v-model="editData.userType">
                    <el-radio v-for="item in orgDegreeItems" :label="item.id" :key="item.id" border>{{ item.name }}</el-radio>
                  </el-radio-group>
                </el-col>
              </el-form-item>
              <el-form-item label="邮箱" prop="email">
                <el-col :span="18">
                  <el-input v-model="editData.email" placeholder="请输入邮箱" auto-complete="off"></el-input>
                </el-col>
              </el-form-item>
              <el-form-item label="状态" prop="status">
                <el-col :span="18">
                  <el-switch v-model="editData.status" active-value="1" inactive-value="0"></el-switch>
                </el-col>
              </el-form-item>
              <el-form-item label="账户生效时间" prop="startValidDate">
                <el-col :span="10">
                  <el-date-picker :picker-options='startValidDate' v-model="editData.startValidDate" type="date"
                    placeholder="选择日期" format="yyyy 年 MM 月 dd 日" value-format="yyyy-MM-dd"></el-date-picker>
                </el-col>
                <el-col :span="14">
                  <span>失效时间</span>
                  <el-date-picker :picker-options='accountExpiredDate' v-model="editData.accountExpiredDate" type="date"
                    placeholder="选择日期" format="yyyy 年 MM 月 dd 日" value-format="yyyy-MM-dd"></el-date-picker>
                </el-col>
              </el-form-item>
              <el-form-item label="密码失效时间">
                <el-date-picker :picker-options='passwordExpiredDate' v-model="editData.passwordExpiredDate" type="date"
                  placeholder="选择日期" format="yyyy 年 MM 月 dd 日" value-format="yyyy-MM-dd"></el-date-picker>
              </el-form-item>
            </el-form>
          </div>
          <span slot="footer" class="dialog-footer">
            <el-button type="primary" @click="handleCheck">保存<i class="el-icon-document-checked el-icon--right"></i></el-button>
            <el-button type="danger" @click="handleCloseCheck(false)">关闭 <i class="el-icon-close"></i></el-button>
          </span>
        </el-dialog>
      </div>
    </div>
  </el-card>
</template>
<script>
  import {
    Tree,
    Dialog,
    Table,
    TableColumn,
    Pagination,
    MessageBox,
    Message,
    Drawer,
    Tag,
    Popover
  } from 'element-ui';
  import {
    userList,
    comboBoxData,
    revisePassWord,
    addOrEditUser,
  } from '@/api/authority/userManage/userManage.js'
  export default {
    name: 'trainInvestigate',
    components: {
      'el-table': Table, //表格
      'el-table-column': TableColumn, //表格列
      'el-pagination': Pagination, //分页
      'el-dialog': Dialog, //对话框
      'el-pagination': Pagination, //分页
      'el-drawer': Drawer, //抽屉
      'el-tag': Tag,
      'el-popover': Popover
    },
    data() {
      var dataList = {
        userName: '',
        email: '',
        userType: '',
        createdTime: '',
        accountExpiredDate: '',
        status: "",
        name: '',
        passwordExpiredDate: '',
        startValidDate: '',
      }
      return {
        textSearch: '', //搜索按钮
        dialogVisible: false, //新增或修改对话框弹出层
        dialogVisibleSearch: false, //高级查询对话框弹出层
        total: 0, //总条数
        pageSize: 20, //每页展示条数
        currentPage: 1, //默认显示页数
        modalTitle: '', //新增或修改弹出层标题
        modalTitleSearch: '', //高级查询弹出层标题
        AdvancedQuery: {},
        accountExpiredDate: '',
        searchData: '', //存储搜索数据
        orgDegreeItems: [],
        tableData: [],
        AdvancedQuery: JSON.parse(JSON.stringify(dataList)),
        dataList: JSON.parse(JSON.stringify(dataList)), // 新增/编辑弹框里的model,用于重置表单
        editData: JSON.parse(JSON.stringify(dataList)),
        roleCodeReadonly: false,
        // 表单验证是否为空
        ruleValidate: {
          userName: [{
            required: true,

            message: '用户名不能为空',

            trigger: 'blur'
          }],
          userType: [{
            required: true,

            message: '此项不能为空',

            trigger: 'blur'
          }],
          email: [{
            type: 'email',
            message: '请输入正确的邮箱地址',
            trigger: ['blur', 'change']
          }]
        },
        //账户生效时间不能早于今天
        startValidDate: {
          disabledDate: time => {
            if (this.editData.accountExpiredDate) {
              return (
                time.getTime() > new Date(this.editData.accountExpiredDate).getTime() || time.getTime() < Date.now() -
                8.64e7 //不能选择的时间值
              )
            } else {
              // 不能大于当前日期
              return time.getTime() < Date.now() - 8.64e7 //不能选择早于今天的时间值
            }
          }
        },
        // 账户失效时间不能早于账户生效时间
        accountExpiredDate: {
          disabledDate: time => {
            if (this.editData.startValidDate) {
              return (
                time.getTime() < new Date(this.editData.startValidDate).getTime() - 8.64e7 // 加- 8.64e7则表示包当天
              )
            } else {
              return time.getTime() < Date.now() - 8.64e7
            }
          }
        },
        //密码失效时间不能早于账户生效时间
        passwordExpiredDate: ''
      };
    },
    created() {
      this.getUserType(); //获取用户类型数据源
      window.onresize = () => {
        this.$refs.tableData.doLayout()
      }
    },
    mounted() {
      this.getUserListOne()
    },
    filters: {
      ellipsis(value) {
        if (!value) return "";
        if (value.length > 3) {
          return value.slice(0, 3) + "...";
        }
        return value;
      }
    },
    methods: {
      // 跳转授权页面
      handleRoleNames(index, row) {
        //动态路由跳转
        this.$router.addRoutes(this.multiRouters([{
          path: 'roleNames',
          name: 'roleNames', //自定义name名称
          component: () => import('@/views/authority/userManage/roleNames'),
          meta: {
            title: '用户角色授权'
          }
        }]));
        this.$router.push(this.routerMatch({
          name: "roleNames", //顶部导航+侧边导航
          params: {
            row: row.roleNameArr,
            rowData: row
          }
        }))
      },
      handleUserGroupNames(index, row) {
        this.$router.addRoutes(this.multiRouters([{
          path: 'userGroupNames',
          name: 'userGroupNames', //自定义name名称
          component: () => import('@/views/authority/userManage/userGroupNames'),
          meta: {
            title: '用户组授权'
          }
        }]));
        this.$router.push(this.routerMatch({
          name: "userGroupNames", //顶部导航+侧边导航
          params: {
            rowData: row,
            row: row.userGroupNameArr
          }
        }))
      },
      //修改状态按钮
      modifyState(index, row) {
        addOrEditUser(row).then(res => {
          if (res.data.code === 10000) {
            Message.success('操作成功')
          }
        })
      },
      // 高级查询
      advancedQuery() {
        this.dialogVisibleSearch = true;
      },
      getUserListOne() { //获取人员数据
        let data = {
          "page": this.currentPage,
          "size": this.pageSize,
          'type': 3
        }
        this.getUserList(data)
      },
      getUserListTwo() { //人员查询
        let data = {
          "page": this.currentPage,
          "size": this.pageSize,
          'type': 1,
          'userName': this.textSearch,
          'name': this.textSearch
        }
        this.getUserList(data)
      },
      getUserListThree() { //高级查询
        let data = {
          "page": this.currentPage,
          "size": this.pageSize,
          'type': 2,
          'userName': this.AdvancedQuery.userName,
          'name': this.AdvancedQuery.name,
          'status': this.AdvancedQuery.status,
          'userType': this.AdvancedQuery.userType,
        }
        this.dialogVisibleSearch = false
        this.getUserList(data)
      },
      getUserList(data) {
        userList(data).then(res => {
          this.tableData = res.data.data.records
          this.total = res.data.data.total
          setTimeout(() => {
            this.$refs.tableData.doLayout();
          }, 0)
        })
      },
      // 每页条数
      handleSizeChange(val) {
        this.pageSize = val
        if(this.textSearch !=''){
          this.getUserListTwo()
        }else{
          this.getUserListOne()
        }
      },
      // 当前页数
      handleCurrentChange(val) {
        this.currentPage = val
        if(this.textSearch !=''){
          this.getUserListTwo()
        }else{
          this.getUserListOne()
        }
      },

      // 高级查询弹框关闭
      searchClose() {
        this.dialogVisibleSearch = false
      },
      // 密码重置
      reset(index, row) {
        MessageBox.confirm('您是否确定密码重置?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          revisePassWord(row.userAccountId).then(res => {
            if (res.data.code === 10000) {
              Message.success('重置成功')
            }
          }).catch(error => {
            console.log(error)
            Message.success('重置失败')
          })

        }).catch(() => {});
      },
      // 获取用户类型数据源
      getUserType() {
        let $this = this;
        comboBoxData('edcea08769bf4adda485fe1794ab5069').then(res => {
          $this.orgDegreeItems = res.data.data;
        });
      },
      // 新增
      handleadd() {
        this.dialogVisible = true;
        this.roleCodeReadonly = false;
        this.modalTitle = "用户信息";
        this.editData = JSON.parse(JSON.stringify(this.dataList))
      },
      /* 过滤无效数据*/
      filterInvalid(dataSource) {
        let validData = {};
        let jsonData = JSON.stringify(dataSource);
        for (let k in dataSource) {
          let data = dataSource[k];
          if (data != '' && data != null && data != undefined && jsonData != "{}" && jsonData != "[]") {
            validData[k] = data;
          }
        }
        return validData;
      },
      //编辑弹框确认 -- 增改
      handleCheck(index, row) {
        var self = this;
        self.$refs.editData.validate(valid => {
          if (valid) {
            self.dialogVisible = false;
            let sendDatas = this.editData
            addOrEditUser(sendDatas).then(res => {
              if (res.data.code === 10000) {
                Message.success("保存成功")
                this.getUserListOne()
              }
            })
          }
        });
      },
      handleEdit(index, row) {
        //编辑
        this.modalTitle = "用户信息";
        this.editData = JSON.parse(JSON.stringify(row));
        this.dialogVisible = true;
        this.roleCodeReadonly = true
      },
      // 弹框关闭 × 按钮
      handleCloseCheck() {
        this.handleAddClose();
        this.$refs.editData.resetFields(); //重置校验
        this.editData = JSON.parse(JSON.stringify(this.dataList))
      },
      // 关闭新增授权按钮
      handleAddClose() {
        this.dialogVisible = false;
        this.$refs.editData.resetFields(); //重置校验
        this.editData = JSON.parse(JSON.stringify(this.dataList))
      },
      restDrawer() { //高级查询重置
        this.dialogVisibleSearch = false
        this.$refs.AdvancedQuery.resetFields()
        this.getUserListOne()
      },
      //保存并添加下一个  暂时备注
      // handleCheckadd(name) {
      //     var self = this;
      //     self.$refs.editData.validate(valid => {
      //       if (valid) {
      //         if (self.modalTitle === "新增用户信息") {
      //           // 获取新增的数据渲染到页面
      //           self.tableData.push(this.editData);
      //           self.editData = {
      //             //编辑弹框数据
      //             userName: '',
      //             email: '',
      //             userType: '',
      //             createdTime: '',
      //             accountExpiredDate: '',
      //             status: '',
      //             name: '',
      //             passwordExpiredDate: '',
      //             startValidDate: ''
      //           };
      //         } else {
      //           // 获取修改的数据渲染到页面
      //           self.tableData[this.index] = this.editData;
      //           self.editData = {
      //             //编辑弹框数据
      //             userName: '',
      //             email: '',
      //             userType: '',
      //             createdTime: '',
      //             accountExpiredDate: '',
      //             status: '',
      //             name: '',
      //             passwordExpiredDate: '',
      //             startValidDate: ''
      //           };
      //         }
      //       } else {
      //         if (self.modalTitle === "新增用户信息") {
      //           Message({
      //             message: "新增失败!"
      //           });
      //         } else {
      //           Message({
      //             message: "修改失败!"
      //           });
      //         }
      //       }
      //     });
      //   },
    }
  };
</script>
<style lang="scss">
  .el-table {
    th {
      padding: 6px 0;
    }

    td {
      padding: 6px 0;
    }
  }

  .el-table__row {
    .cell {
      a {
        color: #409eff;
      }
    }
  }

  .elAdded .el-date-editor.el-input,
  .el-date-editor.el-input__inner {
    width: 190px;
  }

  .table-title-word {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
</style>
